package FileName

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/OS"
	"os"
	"strings"
)

func IsDir(path string) bool {
	file, err := os.Stat(path)
	if err != nil {
		return false
	}
	return file.IsDir()
}

func IsFile(path string) bool {
	file, err := os.Stat(path)
	if err != nil {
		return false
	}
	return !file.IsDir()
}

func GetOsFilePath(filePath string) string {
	if OS.Type.IsWindows() {
		return strings.ReplaceAll(filePath, "/", "\\")
	} else if OS.Type.IsLinux() {
		return strings.ReplaceAll(filePath, "\\", "/")
	} else {
		return strings.ReplaceAll(filePath, "\\", "/")
	}
}

// List 列出目录和文件的名称
func List(dir string) ([]string, error) {
	result := make([]string, 0)

	// 读取目录内容
	files, err := os.ReadDir(dir)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		result = append(result, file.Name())
		continue
	}

	return result, nil
}

func ListFile(dir string, depth, fullName bool) []string {
	return listDirOrFile(dir, depth, fullName, true)
}

func ListDir(dir string, depth, fullName bool) []string {
	return listDirOrFile(dir, depth, fullName, false)
}

func listDirOrFile(dir string, depth, fullName, isFile bool) []string {
	result := make([]string, 0)

	// 检测：是否为目录
	fs, err := os.Stat(dir)
	if err != nil || !fs.IsDir() {
		return result
	}

	// 读取目录内容
	files, err := os.ReadDir(dir)
	if err != nil {
		return result
	}

	for _, file := range files {
		path := GetOsFilePath(dir + "/" + file.Name())

		// 检测：是否为目录
		fs, err = os.Stat(path)
		if err != nil {
			return result
		}

		if isFile && !fs.IsDir() {
			if !fullName {
				result = append(result, fs.Name())
			} else {
				result = append(result, path)
			}
		} else if !isFile && fs.IsDir() {
			if !fullName {
				result = append(result, fs.Name())
			} else {
				result = append(result, path)
			}
		} else if depth {
			// 如果是目录，并且需要深度搜索,回调自身继续查询
			names := listDirOrFile(path, depth, fullName, isFile)
			for _, name := range names {
				result = append(result, name)
			}
		}

	}

	return result
}
